/*
 根据,编排文件,创建应用
 */

<template>
  <div class="app-container">
    <el-row class="wrapper foundNext">
      <el-col :span="24" class="warp-main el-bar">
				<p style="margin-bottom:10px;">
					<i class="iconfont icon-users"></i>创建应用
				</p>
		    <!-- 左边的步骤条.start -->
				<el-col :span="6" style="padding-left:4%;margin-top:30px;">
					<el-steps direction="vertical" :active="2" >
						<el-step title="部署方式" icon="el-icon-load"></el-step>
						<el-step title="编排文件" icon="el-icon-load"></el-step>
						<!-- <el-step title="创建应用" icon="el-icon-load01"></el-step> -->
					</el-steps>
					</el-steps>
				</el-col>
			<!-- 左边的步骤条.end -->

			<!-- 表单.start -->
            <el-col :span="18" style="border-left:1px solid #eaeaea;padding:0 20px;margin-top:30px;">
              <el-form ref="complseFileForm" :model="complseFileForm" :rules="complseFileRules" label-width="80px">
                <el-form-item label="应用名称" prop="appName">
                  <el-input v-model="complseFileForm.appName" style="width:50%;" placeholder="请输入应用名称"></el-input>
                </el-form-item>
                <el-form-item label="应用描述" prop="described">
                  <el-input v-model="complseFileForm.described" style="width:50%;" placeholder="请输入应用描述"></el-input>
                </el-form-item>
                <el-form-item label="编排文件">
                  <el-upload
                    class="upload-demo"
					ref="uploadFile"
					:data="uploadFileData"
					:headers="uploadHeaders"
                    drag
                    action="http://venus-api.venus.me/api-app/app-admin/app-create/upload-file"
					:multiple="false"
					:auto-upload="false"
					:limit="1"
					:on-success="handleAvatarSuccess"
					:on-error="handleAvatarError"
					:before-upload="beforeAvatarUpload"
                    :on-exceed="handleExceed"
					style="line-height:0;">
                    <i class="el-icon-upload"></i>
                  </el-upload>

					<!-- <el-upload
						class="upload-demo"
						ref="uploadFile"
						action="handleFile"
						:data="uploadFileData"
						:limit="1"
						:before-upload="beforeAvatarUpload"
						:on-exceed="handleExceed"
						:auto-upload="false">
						<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
					</el-upload> -->

                  <div class="el-upload__text">方式一:<em>点击上传,只能上传 yaml文件，如何文件太大就是闪退</em></div>
                  <div class="el-upload__text">方式二:<em>将yaml文件内容粘贴到下面文本域</em></div>
                  <div class="el-upload__text">提示:<em>yaml文件中的namespace必须和当前选择的空间名称一致</em></div>
                </el-form-item>

                <el-form-item label="编排内容">
                  <!-- 编辑器 -->
                  <div class="edit_title">Yaml（读写）
                    <i class="el-icon-edit" style="color:#999;"></i>
                  </div>
                  <!-- advanced -->
                  <codemirror
                    :value="code"
					:cursorHeight="0.85"
                    ref="myEditor"
					@change="codeChange">
                  </codemirror>
                </el-form-item>

				<div class="form-btn" align="right">
					<el-form-item >
						<el-button class="iconfont icon-fanhui"  @click="back">上一步</el-button>
            			<el-button class="iconfont icon-tianjia2" type="primary" @click="createApp">创建应用</el-button>
					</el-form-item>
				</div>

              </el-form>
            </el-col>
			<!-- 表单.end -->
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Vue from "vue";
import { codemirror } from "vue-codemirror-lite";

//import codemirror from 'codemirror/lib/codemirror'   // CodeMirror，必要
import "codemirror/lib/codemirror.css"; // css，必要
import "codemirror/mode/javascript/javascript"; // js的语法高亮，自行替换为你需要的语言

export default {
  components: {
    // 编辑域组件
    codemirror
  },
  data() {
    // 表单校验
    const validateAppName = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("应用名称长度不能少于3"));
      } else {
        //callback();
        let param = {
            appName: value
        }
        // 后台验证
        this.httpClient
          .httpClientget(
            this.projectConfig.URL_API_APP_MANAGE_APP_NAME ,
            param
          )
          .then(res => {
            const code = res.data;
            if (code == this.projectConfig.CODE_OK) {
              callback(new Error("应用名称已经存在"));
            } else {
              callback();
            }
          });
      }
    };

    const validateAppDescribed = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("应用描述长度不能少于3"));
      } else {
        callback();
      }
    };

    return {
      // 编辑域初始化的值
      code: "",
      // 编辑文本域的数据
      codeMirrorData: "",
      // 编排文件的表单
      complseFileForm: {
        appName: "", // 应用名称
        described: "", // 应用描述
        fileData: "", // yaml文件内容
        namespace: "", // 当前选择的空间名
        deployType: 0 // 当前部署方式
      },
      //
      activeName2: "first",
      // 左边的步骤条
      active: "1",
      // 表单校验规则
      complseFileRules: {
        appName: [
          { required: true, trigger: "blur", validator: validateAppName }
        ],
        described: [
          { required: true, trigger: "blur", validator: validateAppDescribed }
        ]
      },
      // 上传文件额外携带的参数
      uploadFileData: {
        appName: "", // 应用名称
        described: "", // 应用描述
        namespace: "", // 当前选择的空间名
        deployType: 0 // 当前部署方式
      },
      // 上传文件动作头部
      uploadHeaders: {
        "X-Token": this.$store.getters.token
      }
    };
  },
  computed: {
    editor() {
      // get current editor object
      return this.$refs.myEditor.edito;
    }
  },
  methods: {
    back() {
      this.$router.push({
        path: "/apply/management/app_create"
      });
    },
    // 上传文件前
    beforeAvatarUpload(file) {
      //console.log(file);
      // 判断文件是否为空
      if (file != null || file != "") {
        let fileName = file.name;
        // 只能通过yaml文件来保存
        if (fileName.indexOf("yaml") == -1) {
          this.$notify.warning({
            message: "请选择yaml编排文件"
          });
          return false;
        }
      }

      // 操作审计
      this.userBaseInfo.setOperObjectName(this.complseFileForm.appName);
      // 验证通过,调用创建方法
      this.createAppByUploadFile();

      return true;
    },
    // 上传文件成功,回调
    handleAvatarSuccess(res, file) {
      let _code = res.data.statusCode;
      let _msg = res.data.message;
      if (_code == this.projectConfig.CODE_OK) {
        this.$notify.success("成功创建应用");
      } else {
        this.$notify.error(_msg);
      }

      // 跳转到展示页面
      this.$router.push({
        path: "/apply/management/app_page"
      });
    },
    // 上传文件,失败
    handleAvatarError(err, file) {
      this.$notify.error("上传文件失败,请重新上传");
    },
    // 超出选择文件个数
    handleExceed(files, fileList) {
      this.$notify.warning("只能选择一个编排文件");
    },
    // 编辑文本域改变的时候
    codeChange(object) {
      // 当编辑文本域输入改变的时候,赋值
      this.codeMirrorData = object;
      //console.log('codemirror=' + object);
    },
    // 通过粘贴的yaml文件内容创建
    createAppByYamlFile() {
      // 获得编辑域的内容
      const yamlFileContent = this.codeMirrorData;

      if (yamlFileContent.length < 10 || yamlFileContent == null) {
        return false;
      }

      // 简单的校验yaml文件格式
      if (
        yamlFileContent.indexOf("kind: ") == -1 ||
        yamlFileContent.indexOf("apiVersion: ") == -1 ||
        yamlFileContent.indexOf("metadata:") == -1
      ) {
        this.$notify.error({
          message: "Yaml文件语法有误"
        });
        return false;
      }

      // 只能在当前选择的空间里面创建应用
      // 分割
      const yamlArr = yamlFileContent.split("---\n");
      if (yamlFileContent.indexOf("---\r\n") != -1) {
        const yamlArr = yamlFileContent.split("\r\n");
      }

      // 遍历
      for (let i = 0; i < yamlArr.length; i++) {
        let str = yamlArr[i];
        if (str == "") continue;
        let currentNamespace1 = "namespace: " + this.$store.getters.namespace;
        if (str.indexOf(currentNamespace1) == -1) {
          this.$notify.error({
            message: "Yaml文件中的空间名称和当前选择的空间不一样"
          });
          return false;
        }
      }

      // 验证通过
      // 获得当前值
      this.complseFileForm.namespace = this.$store.getters.namespace;
      this.complseFileForm.fileData = yamlFileContent;

      // 创建应用
      //console.log('complseFileForm = ' + JSON.stringify(this.complseFileForm));
      // 操作审计
      this.userBaseInfo.setOperObjectName(this.complseFileForm.appName);
      // post 后台
      this.httpClient
        .httpClientPost(
          this.projectConfig.URL_API_APP_MANAGE_CREATE_COMPOSE_FILE,
          this.complseFileForm
        )
        .then(res => {
          let _code = res.data.statusCode;
          let _msg = res.data.message;

          if (_code == this.projectConfig.CODE_OK) {
            this.$notify.success("成功创建应用");
          } else {
            this.$notify.error(_msg);
          }

          // 跳转到展示页面
          this.$router.push({
            path: "/apply/management/app_page"
          });
        });
    },
    // 通过上传文件的方式创建应用
    createAppByUploadFile() {
      // 赋值
      this.uploadFileData.appName = this.complseFileForm.appName;
      this.uploadFileData.described = this.complseFileForm.described;
      this.uploadFileData.namespace = this.$store.getters.namespace;
    },
    createApp() {
      /* this.$router.push({
				path: "/apply/management/app_page"
			}); */

      //表单校验
      this.$refs.complseFileForm.validate(valid => {
        if (valid) {
          // 1:上传文件
          this.$refs.uploadFile.submit();

          // 2:编辑域方式创建
          this.createAppByYamlFile();
        } else {
          return false;
        }
      });

      // 获得选择文件个数
      //const selectedFilesNum = this.$refs.uploadFile.fileList.length;
      //console.log(this.$refs.uploadFile);

      // 1:如果选择文件数量不为空,则根据选择的文件创建应用
      // if	(selectedFilesNum > 0 ) {
      // 	this.$refs.uploadFile.submit();
      // } else if (yamlFileContent.length != 0 || yamlFileContent != '') {
      // 	// 2: 根据输入的yaml文件内容创建应用

      // } else {
      // 	// 3: 应用创建不通过
      // 	this.$notify.warning({
      // 		message: '请选择其中一种方式创建应用'
      // 	});
      // }
    }
  }
};
</script>
<style>
.foundNext .el-step__head {
  margin-bottom: 60px;
}
.foundNext .el-upload-dragger {
  width: 64px;
  height: 64px;
}
.foundNext .step {
  width: 100%;
  text-align: right;
  padding-top: 10px;
}

.foundNext .el-step__title {
  font-size: 16px;
}
.foundNext .el-upload-dragger .el-icon-upload {
  font-size: 42px;
  color: #97a8be;
  margin: 4px;
}

.foundNext .el-upload-list .el-upload-list__item {
  width: 180px;
  margin-right: 40px;
  margin-top: 10px;
}
.foundNext .el-step__icon {
  font-size: 22px;
}
.foundNext .el-step__icon .el-icon-load {
  width: 30px;
  height: 30px;
  background: url(../../../assets/images/Cloud-down.png);
  background-size: 30px 30px;
}
.foundNext .el-step__icon .el-icon-load01 {
  width: 30px;
  height: 30px;
  background: url(../../../assets/images/Cloud-down-no.png);
  background-size: 30px 30px;
}
.foundNext .el-step__line.is-vertical {
  top: 30px;
}
.edit_title {
  width: 100%;
  height: 40px;
  background:#000;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  padding: 0 10px;
	box-sizing: border-box;
	color:#d1cfcf;
}
.CodeMirror-gutters{
	background: #000;
	border-right:0;
}
.CodeMirror {
  position: relative;
  overflow: hidden;
  background: #000;
	color:#fff;
}
.CodeMirror-wrap pre{
	height: 24px;
}
.CodeMirror-scroll {
  overflow: auto !important;
  margin-bottom: 0px;
  margin-right: 0px;
  padding-bottom: 0px;
  margin-top: 0;
}
.foundNext .el-step.is-vertical .el-step__line {
  width: 1px;
  top: 0;
  bottom: -60px;
  left: 16px;
}

</style>
